package com.dong.common.data;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 自定义 通用实体构造器
 * <p>
 * 也可以使用Lombok的@Builder注解
 *
 * @author zhaodc
 * @date 2021/9/9 10:29
 **/
public final class EntityBuilder<T> {

    private final Supplier<T> instantiator;
    private final List<Consumer<T>> modifiers = new LinkedList<>();

    public EntityBuilder(Supplier<T> instantiator) {
        this.instantiator = instantiator;
    }

    public static <T> EntityBuilder<T> of(Supplier<T> instantiator) {
        return new EntityBuilder<>(instantiator);
    }

    public <F> EntityBuilder<T> with(ConsumerFor1Filed<T, F> filedConsumer, F filedValue) {
       /*
        Consumer<T> c = new Consumer<T>() {
            @Override
            public void accept(T t) {
                consumer.accept(t, filedValue);
            }
        };
        modifiers.add(c);
        */
        modifiers.add(t -> filedConsumer.accept(t,filedValue));
        return this;
    }

    public T build() {
        T value = instantiator.get();
        //调用setter方法给属性赋值
        modifiers.forEach(tConsumer -> tConsumer.accept(value));
        modifiers.clear();
        return value;
    }

    /**
     * 1 参数 Consumer
     */
    @FunctionalInterface
    public interface ConsumerFor1Filed<T, P1> {
        void accept(T t, P1 p1);
    }

}
